package com.cc.common.interceptor

import com.cc.common.anno.NoLogin
import jakarta.servlet.http.HttpServletRequest
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.HandlerInterceptor
import java.io.IOException

/**
 * 登录权限拦截器
 *
 * @author cc
 * @version 1.0
 * @since 2023/9/15
 */
@Component
class AuthInterceptor : HandlerInterceptor {
    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        // OPTIONS请求直接return
        if (HttpMethod.OPTIONS.toString() == request.method) {
            response.status = HttpStatus.NO_CONTENT.value()
            return false
        }

        val isHandler = handler is HandlerMethod
        if (!isHandler) {
            return true
        }

        //不需要登录
        val noNeedLogin: NoLogin? = (handler as HandlerMethod).getMethodAnnotation(NoLogin::class.java)
        // 无token 无需登录
        if (null != noNeedLogin) {
            return true
        }
        val session = request.session
        val attribute = session.getAttribute("usr")
        if (attribute == null) {
            response.sendRedirect("/login")
            return false
        }

        return true
    }

    /**
     * 错误输出
     *
     * @param response 响应
     * @param resVO    响应结果
     * @throws IOException io异常
     */
//    @Throws(IOException::class)
//    private fun outputResult(response: HttpServletResponse, resVO: ResVO<String>) {
//        val msg: String = JsonUtils.toJsonString(resVO)
//        response.setContentType("application/json;charset=UTF-8")
//        response.getWriter().write(msg)
//        response.flushBuffer()
//    }
}
